# -*- coding: utf-8 -*-
# @Time    : 2022/1/21 16:47
# @Author  : Mr.Ye
# @Email   : a3289748713@163.com
# @File    : views.py
# @Software: PyCharm
from wtforms import ValidationError

from . import admin
from .forms import LoginForm
from flask import session, request, redirect, url_for, render_template, flash
from MyVideo import db
from MyVideo.models import Admin, AdminLog, Role
from datetime import datetime
from functools import wraps
from flask_login import login_user


def admin_login_req(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if "admin" not in session:
            return redirect(url_for("admin.login", next=request.url))
        return f(*args, **kwargs)

    return decorated_function


@admin.route("/index")
@admin_login_req
def index():
    return render_template('admin/index.html')


@admin.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        get_data = form.data
        user = Admin.query.filter_by(name=get_data['account']).first()
        # 用户名没有的情况下
        if user is None:
            flash('帐号未注册！', category="error")

        if user and user.verify_password(form.password.data):
            login_user(user, remember=form.remember_me.data)

            session['admin'] = form.account.data
            session['admin_id'] = user.id

            admin_log = AdminLog(
                admin_id=user.id,
                ip=request.remote_addr,
                add_time=datetime.now()
            )
            db.session.add(admin_log)
            db.session.commit()
            return redirect(request.args.get('next') or url_for('admin.index'))

    return render_template('admin/login.html', title='登录', form=form)


@admin.route('/role/list/<int:page>/', methods=['GET'])
@admin_login_req
def role_list(page=None):
    if page is None:
        page = 1

    page_data = Role.query.order_by(
        Role.add_time.desc()
    ).paginate(page, per_page=10)

    return render_template("admin/role_list.html", page_data=page_data)
